const log4js = require('log4js');
const config = require('config');
const path = require('path');

log4js.configure({
  appenders: {
    console: {
      type: 'console',
    },
    app: {
      type: 'file',
      filename: path.resolve(__dirname, '../../logs/app'),
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true,
    },
    errorFile: {
      type: 'file',
      filename: path.resolve(__dirname, '../../logs/errors'),
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true,
    },
    errors: {
      type: 'logLevelFilter',
      level: 'ERROR',
      appender: 'errorFile',
    },
  },
  categories: {
    default: { appenders: ['console'], level: 'ALL' },
    app: { appenders: ['app', 'errors'], level: 'ALL' },
  },
});

var logType = '';
switch (config.get('logMode')) {
  case 'pro':
    logType = 'app';
    break;
  default:
    logType = 'console';
}
var logger = log4js.getLogger(logType);

// logger.trace("Entering cheese testing");
// logger.debug("Got cheese.");
// logger.info("Cheese is Comté.");
// logger.warn("Cheese is quite smelly.");
// logger.error("Cheese is too ripe!");
// logger.fatal("Cheese was breeding ground for listeria.");

logger.print = function (url, params, result, time, tag, method, statusCode) {
  let s = '';
  tag && (s += `[${tag}]`);
  method && (s += `[${method}]`);
  statusCode && (s += `[status=> ${statusCode}]`);
  s += `[url=> ${url}]`;
  if (params) {
    params._req_ && delete params._req_;
    s += `[params=> ${JSON.stringify(params)}]`;
  }
  time && (s += `[start=> ${new Date(time).toLocaleString()}.${time % 1000} cost=>${Date.now() - time}ms]`);
  result && (s += `[result => ${result.length > 1000 ? result.substring(0, 2000) + '...' : result}]`);
  this.info(s);
};

logger.echo = function (tag, message) {
  let s = `[${tag}] ${message}`;
  this.info(s);
};

logger.use = function (app) {
  app.use(
    log4js.connectLogger(logger, {
      level: 'INFO',
      format: ':method :status :url :response-time ms',
    })
  );
};

exports = module.exports = logger;
